package com.lhkj.ct.meta.modules.gauge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lhkj.ct.base.model.Option;
import com.lhkj.ct.base.model.dto.PageQuery;
import com.lhkj.ct.base.mybatis.core.metadata.SqlOrder;
import com.lhkj.ct.base.mybatis.extension.service.impl.IServiceImpl;
import com.lhkj.ct.meta.modules.gauge.mapper.GaugeCategoryMapper;
import com.lhkj.ct.meta.modules.gauge.model.entity.TblGaugeCategory;
import com.lhkj.ct.meta.modules.gauge.service.GaugeCategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 量表/问卷类别 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2023-10-08
 */
@Service
public class GaugeCategoryServiceImpl extends IServiceImpl<GaugeCategoryMapper, TblGaugeCategory> implements GaugeCategoryService {

    @Override
    public IPage<TblGaugeCategory> selectCategoryPage(TblGaugeCategory category, PageQuery pageQuery) {
        LambdaQueryWrapper<TblGaugeCategory> wrapper = new LambdaQueryWrapper<TblGaugeCategory>()
                .like(StringUtils.isNotBlank(category.getCName()), TblGaugeCategory::getCName, category.getCName())
                .eq(Objects.nonNull(category.getCType()), TblGaugeCategory::getCType, category.getCType());
        return getBaseMapper().selectCategoryPage(generatePageDesc(pageQuery, TblGaugeCategory::getCreateTime), wrapper);
    }

    @Override
    public IPage<Option<String>> selectCategoryOptions(TblGaugeCategory category, PageQuery pageQuery) {
        LambdaQueryWrapper<TblGaugeCategory> wrapper = new LambdaQueryWrapper<TblGaugeCategory>()
                .like(StringUtils.isNotBlank(pageQuery.getKeywords()), TblGaugeCategory::getCName, pageQuery.getKeywords())
                .eq(Objects.nonNull(category.getCType()), TblGaugeCategory::getCType, category.getCType());
        Page<TblGaugeCategory> page = generatePage(pageQuery, SqlOrder.desc(TblGaugeCategory::getCreateTime));
        return getBaseMapper().selectCategoryOptions(page, wrapper);
    }

    @Override
    public boolean checkNameUnique(TblGaugeCategory category) {
        LambdaUpdateWrapper<TblGaugeCategory> wrapper = new LambdaUpdateWrapper<TblGaugeCategory>()
                .like( TblGaugeCategory::getCName, category.getCName())
                .eq( TblGaugeCategory::getCType, category.getCType());
        wrapper.last("limit 1");
        TblGaugeCategory target = getBaseMapper().selectOne(wrapper);
        return null == target || StringUtils.equals(target.getId(), category.getId());
    }
}
